package com.course02.order_backend.security.LXY;

// 如果登录成功,使用当前用户进行访问，发现权限不够，报权限错误，定义处理器进行处理

import cn.hutool.json.JSONUtil;
import com.course02.order_backend.dto.LXY.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 权限不足处理器
 * 用户登录成功，访问某一个资源时因为权限不足，报异常
 */
@Component
public class LoginUnAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Result result = Result.error("权限不足,请重新授权。");
        //将消息json化
        String json = JSONUtil.toJsonStr(result);
        //送到客户端
        response.getWriter().print(json);
    }
}

//自定义权限不足处理器后，需要进行注册，注册到SecurityConfig配置文件中
